<!DOCTYPE html>
<html lang="zh-CN" xmlns:th="http://www.thymeleaf.org">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>购物车 - 商品商城</title>
    <link href="https://cdn.jsdelivr.net/npm/bootstrap@5.3.0/dist/css/bootstrap.min.css" rel="stylesheet">
    <link href="https://cdn.jsdelivr.net/npm/bootstrap-icons@1.10.0/font/bootstrap-icons.css" rel="stylesheet">
    <link href="/css/shop.css" rel="stylesheet">
    <style>
        .cart-container {
            background-color: #fff;
            border-radius: 8px;
            box-shadow: 0 2px 10px rgba(0, 0, 0, 0.1);
            padding: 20px;
            margin-bottom: 20px;
        }
        
        .cart-item {
            border-bottom: 1px solid #eee;
            padding: 15px 0;
            position: relative;
        }
        
        .cart-item:last-child {
            border-bottom: none;
        }
        
        .cart-item-image {
            width: 80px;
            height: 80px;
            object-fit: cover;
            border-radius: 4px;
            border: 1px solid #eee;
        }
        
        .cart-item-info {
            flex: 1;
        }
        
        .cart-item-name {
            font-weight: 500;
            margin-bottom: 5px;
            color: #333;
        }
        
        .cart-item-price {
            color: #e74a3b;
            font-weight: 600;
            font-size: 16px;
        }
        
        .cart-item-subtotal {
            color: #e74a3b;
            font-weight: 600;
            font-size: 18px;
        }
        
        .quantity-selector {
            display: flex;
            align-items: center;
            border: 1px solid #ddd;
            border-radius: 4px;
            width: 120px;
        }
        
        .quantity-selector button {
            border: none;
            background: #f8f9fa;
            width: 30px;
            height: 30px;
            display: flex;
            align-items: center;
            justify-content: center;
            cursor: pointer;
        }
        
        .quantity-selector button:hover {
            background: #e9ecef;
        }
        
        .quantity-selector input {
            border: none;
            text-align: center;
            width: 60px;
            height: 30px;
        }
        
        .cart-summary {
            background-color: #f8f9fc;
            border-radius: 8px;
            padding: 20px;
        }
        
        .cart-summary h5 {
            margin-bottom: 15px;
            font-weight: 600;
        }
        
        .summary-item {
            display: flex;
            justify-content: space-between;
            margin-bottom: 10px;
        }
        
        .summary-total {
            font-size: 18px;
            font-weight: 600;
            color: #e74a3b;
            border-top: 1px solid #ddd;
            padding-top: 10px;
            margin-top: 10px;
        }
        
        .empty-cart {
            text-align: center;
            padding: 40px 0;
        }
        
        .empty-cart i {
            font-size: 64px;
            color: #ddd;
            margin-bottom: 20px;
        }
        
        .invalid-item {
            opacity: 0.6;
            background-color: #f8f9fa;
        }
        
        .invalid-badge {
            background-color: #6c757d;
            color: white;
            font-size: 12px;
            padding: 2px 6px;
            border-radius: 3px;
            margin-left: 5px;
        }
        
        .cart-actions {
            margin-top: 20px;
            display: flex;
            justify-content: space-between;
        }
        
        .cart-select-all {
            display: flex;
            align-items: center;
        }
        
        .cart-batch-actions {
            display: flex;
            gap: 10px;
        }
        
        .checkout-btn {
            background: linear-gradient(135deg, #e74a3b 0%, #c0392b 100%);
            border: none;
            color: white;
            font-weight: 600;
            padding: 12px 30px;
            border-radius: 4px;
            transition: all 0.3s ease;
        }
        
        .checkout-btn:hover {
            background: linear-gradient(135deg, #c0392b 0%, #a93226 100%);
            transform: translateY(-2px);
            box-shadow: 0 4px 8px rgba(231, 74, 59, 0.3);
        }
        
        .checkout-btn:disabled {
            background: #ccc;
            cursor: not-allowed;
            transform: none;
            box-shadow: none;
        }
    </style>
</head>
<body>
    <!-- 导航栏 -->
    <nav class="navbar navbar-expand-lg navbar-light bg-white shadow-sm sticky-top">
        <div class="container">
            <a class="navbar-brand" href="/shop">
                <i class="bi bi-shop"></i> 商品商城
            </a>
            <button class="navbar-toggler" type="button" data-bs-toggle="collapse" data-bs-target="#navbarNav">
                <span class="navbar-toggler-icon"></span>
            </button>
            <div class="collapse navbar-collapse" id="navbarNav">
                <ul class="navbar-nav me-auto">
                    <li class="nav-item">
                        <a class="nav-link" href="/shop">首页</a>
                    </li>
                    <li class="nav-item">
                        <a class="nav-link" href="/shop/products">所有商品</a>
                    </li>
                    <li class="nav-item">
                        <a class="nav-link" href="/shop/categories">商品分类</a>
                    </li>
                    <li class="nav-item">
                        <a class="nav-link" href="/shop/promotions">促销商品</a>
                    </li>
                </ul>
                <form class="d-flex me-3" action="/shop/search" method="get">
                    <input class="form-control me-2" type="search" name="keyword" placeholder="搜索商品...">
                    <button class="btn btn-outline-primary" type="submit">
                        <i class="bi bi-search"></i>
                    </button>
                </form>
                <ul class="navbar-nav">
                    <li class="nav-item dropdown">
                        <a class="nav-link dropdown-toggle" href="#" id="navbarDropdown" role="button" data-bs-toggle="dropdown">
                            <i class="bi bi-person-circle"></i> 我的账户
                        </a>
                        <ul class="dropdown-menu">
                            <li><a class="dropdown-item" href="/auth/login">登录</a></li>
                            <li><a class="dropdown-item" href="/auth/register">注册</a></li>
                            <li><hr class="dropdown-divider"></li>
                            <li><a class="dropdown-item" href="/shop/profile">个人中心</a></li>
                            <li><a class="dropdown-item" href="/shop/orders">我的订单</a></li>
                            <li><a class="dropdown-item active" href="/shop/cart">购物车</a></li>
                        </ul>
                    </li>
                </ul>
            </div>
        </div>
    </nav>

    <!-- 页面头部 -->
    <div class="page-header">
        <div class="container">
            <h1 class="fw-bold">我的购物车</h1>
            <p class="lead mb-0">管理您选择的商品</p>
        </div>
    </div>

    <div class="container mb-5">
        <div class="row">
            <!-- 购物车列表 -->
            <div class="col-lg-9">
                <div class="cart-container">
                    <!-- 购物车为空 -->
                    <div th:if="${#lists.isEmpty(cartItems)}" class="empty-cart">
                        <i class="bi bi-cart-x"></i>
                        <h4>您的购物车是空的</h4>
                        <p class="text-muted">快去挑选心仪的商品吧！</p>
                        <a href="/shop" class="btn btn-primary">
                            <i class="bi bi-arrow-left me-2"></i>继续购物
                        </a>
                    </div>

                    <!-- 购物车有商品 -->
                    <div th:if="${!#lists.isEmpty(cartItems)}">
                        <!-- 购物车操作栏 -->
                        <div class="cart-actions">
                            <div class="cart-select-all">
                                <input type="checkbox" id="selectAll" class="form-check-input me-2">
                                <label for="selectAll" class="form-check-label">全选</label>
                            </div>
                            <div class="cart-batch-actions">
                                <button class="btn btn-outline-danger btn-sm" id="deleteSelected">
                                    <i class="bi bi-trash me-1"></i>删除选中
                                </button>
                                <button class="btn btn-outline-secondary btn-sm" id="clearCart">
                                    <i class="bi bi-trash3 me-1"></i>清空购物车
                                </button>
                            </div>
                        </div>

                        <!-- 购物车商品列表 -->
                        <div class="mt-3">
                            <div th:each="cartItem : ${cartItems}" 
                                 th:classappend="${!cartItem.valid} ? 'invalid-item' : ''"
                                 class="cart-item" 
                                 th:data-product-id="${cartItem.productId}">
                                <div class="d-flex align-items-center">
                                    <!-- 选择框 -->
                                    <div class="me-3">
                                        <input type="checkbox" 
                                               class="form-check-input item-checkbox" 
                                               th:checked="${cartItem.selected}"
                                               th:disabled="${!cartItem.valid}">
                                    </div>

                                    <!-- 商品图片 -->
                                    <div class="me-3">
                                        <img th:src="${cartItem.productImage ?: '/images/product-placeholder.jpg'}" 
                                             th:alt="${cartItem.productName}"
                                             class="cart-item-image">
                                    </div>

                                    <!-- 商品信息 -->
                                    <div class="cart-item-info me-3">
                                        <div class="cart-item-name">
                                            <span th:text="${cartItem.productName}">商品名称</span>
                                            <span th:if="${!cartItem.valid}" class="invalid-badge">
                                                <span th:if="${cartItem.productStatus != 1}">已下架</span>
                                                <span th:if="${cartItem.productStatus == 1 and cartItem.stockQuantity <= 0}">库存不足</span>
                                            </span>
                                        </div>
                                        <div class="text-muted small">
                                            商品编码: <span th:text="${cartItem.productId}">商品编码</span>
                                        </div>
                                        <div class="cart-item-price">
                                            ¥<span th:text="${#numbers.formatDecimal(cartItem.productPrice, 1, 2)}">0.00</span>
                                        </div>
                                    </div>

                                    <!-- 数量选择器 -->
                                    <div class="me-3">
                                        <div class="quantity-selector">
                                            <button type="button" class="decrease-btn" th:disabled="${cartItem.quantity <= 1 or !cartItem.valid}">
                                                <i class="bi bi-dash"></i>
                                            </button>
                                            <input type="number" 
                                                   class="quantity-input" 
                                                   th:value="${cartItem.quantity}" 
                                                   min="1" 
                                                   th:max="${cartItem.stockQuantity}"
                                                   th:disabled="${!cartItem.valid}">
                                            <button type="button" class="increase-btn" th:disabled="${cartItem.quantity >= cartItem.stockQuantity or !cartItem.valid}">
                                                <i class="bi bi-plus"></i>
                                            </button>
                                        </div>
                                        <div class="text-muted small mt-1" th:if="${cartItem.valid}">
                                            库存: <span th:text="${cartItem.stockQuantity}">0</span>
                                        </div>
                                    </div>

                                    <!-- 小计金额 -->
                                    <div class="me-3">
                                        <div class="cart-item-subtotal">
                                            ¥<span th:text="${#numbers.formatDecimal(cartItem.subtotal, 1, 2)}">0.00</span>
                                        </div>
                                    </div>

                                    <!-- 删除按钮 -->
                                    <div>
                                        <button type="button" class="btn btn-outline-danger btn-sm delete-item">
                                            <i class="bi bi-trash"></i>
                                        </button>
                                    </div>
                                </div>
                            </div>
                        </div>
                    </div>
                </div>
            </div>

            <!-- 购物车汇总 -->
            <div class="col-lg-3">
                <div class="cart-summary">
                    <h5>订单汇总</h5>
                    
                    <div class="summary-item">
                        <span>商品总数:</span>
                        <span th:text="${statistics.totalItems}">0</span>
                    </div>
                    
                    <div class="summary-item">
                        <span>已选商品:</span>
                        <span th:text="${statistics.selectedItems}">0</span>
                    </div>
                    
                    <div class="summary-item">
                        <span>有效商品:</span>
                        <span th:text="${statistics.validItems}">0</span>
                    </div>
                    
                    <div class="summary-item summary-total">
                        <span>总计:</span>
                        <span>¥<span th:text="${#numbers.formatDecimal(statistics.totalAmount, 1, 2)}">0.00</span></span>
                    </div>
                    
                    <div class="d-grid mt-4">
                        <button type="button" class="btn checkout-btn" id="checkoutBtn" 
                                th:disabled="${statistics.selectedItems == 0 or statistics.validItems == 0}">
                            <i class="bi bi-credit-card me-2"></i>去结算
                        </button>
                        
                        <a href="/shop" class="btn btn-outline-secondary mt-2">
                            <i class="bi bi-arrow-left me-2"></i>继续购物
                        </a>
                    </div>
                </div>
            </div>
        </div>
    </div>

    <!-- 页脚 -->
    <footer class="footer">
        <div class="container">
            <div class="row">
                <div class="col-md-4">
                    <h5>商品商城</h5>
                    <p>提供优质商品，满足您的购物需求</p>
                </div>
                <div class="col-md-4">
                    <h5>快速链接</h5>
                    <ul>
                        <li><a href="/shop">首页</a></li>
                        <li><a href="/shop/products">所有商品</a></li>
                        <li><a href="/shop/categories">商品分类</a></li>
                        <li><a href="/shop/promotions">促销商品</a></li>
                    </ul>
                </div>
                <div class="col-md-4">
                    <h5>客户服务</h5>
                    <ul>
                        <li><a href="#">帮助中心</a></li>
                        <li><a href="#">退换货政策</a></li>
                        <li><a href="#">配送说明</a></li>
                        <li><a href="#">联系我们</a></li>
                    </ul>
                </div>
            </div>
            <div class="footer-bottom">
                <p>&copy; 2023 商品商城. 保留所有权利.</p>
            </div>
        </div>
    </footer>

    <script src="https://cdn.jsdelivr.net/npm/bootstrap@5.3.0/dist/js/bootstrap.bundle.min.js"></script>
    <script>
        document.addEventListener('DOMContentLoaded', function() {
            // 通用的提示函数
            function showToast(message, type = 'info') {
                // 创建toast容器（如果不存在）
                let toastContainer = document.querySelector('.toast-container');
                if (!toastContainer) {
                    toastContainer = document.createElement('div');
                    toastContainer.className = 'toast-container position-fixed bottom-0 end-0 p-3';
                    toastContainer.style.zIndex = '11';
                    document.body.appendChild(toastContainer);
                }
                
                // 创建toast元素
                const toastId = 'toast-' + Date.now();
                const toastHtml = `
                    <div id="${toastId}" class="toast" role="alert" aria-live="assertive" aria-atomic="true">
                        <div class="toast-header">
                            <i class="bi bi-${type === 'success' ? 'check-circle-fill text-success' : 
                                           type === 'danger' ? 'exclamation-triangle-fill text-danger' : 
                                           type === 'warning' ? 'exclamation-triangle-fill text-warning' : 
                                           'info-circle-fill text-info'} me-2"></i>
                            <strong class="me-auto">${type === 'success' ? '成功' : 
                                                type === 'danger' ? '错误' : 
                                                type === 'warning' ? '警告' : '提示'}</strong>
                            <button type="button" class="btn-close" data-bs-dismiss="toast" aria-label="Close"></button>
                        </div>
                        <div class="toast-body">
                            ${message}
                        </div>
                    </div>
                `;
                
                toastContainer.insertAdjacentHTML('beforeend', toastHtml);
                
                // 显示toast
                const toastElement = document.getElementById(toastId);
                const toast = new bootstrap.Toast(toastElement);
                toast.show();
                
                // 监听隐藏事件，从DOM中移除
                toastElement.addEventListener('hidden.bs.toast', function() {
                    toastElement.remove();
                });
            }
            
            // 全局函数，供其他地方使用
            window.showToast = showToast;
            const selectAllCheckbox = document.getElementById('selectAll');
            const itemCheckboxes = document.querySelectorAll('.item-checkbox');
            const checkoutBtn = document.getElementById('checkoutBtn');
            const deleteSelectedBtn = document.getElementById('deleteSelected');
            const clearCartBtn = document.getElementById('clearCart');
            
            // 全选/取消全选
            selectAllCheckbox.addEventListener('change', function() {
                const selected = this.checked;
                itemCheckboxes.forEach(checkbox => {
                    if (!checkbox.disabled) {
                        checkbox.checked = selected;
                    }
                });
                updateCartStatistics();
                updateSelectedAll(selected);
            });
            
            // 单个商品选择
            itemCheckboxes.forEach(checkbox => {
                checkbox.addEventListener('change', function() {
                    updateSelectAllCheckbox();
                    updateCartStatistics();
                    updateSelected(this.closest('.cart-item').dataset.productId, this.checked);
                });
            });
            
            // 更新全选复选框状态
            function updateSelectAllCheckbox() {
                const enabledCheckboxes = Array.from(itemCheckboxes).filter(cb => !cb.disabled);
                const checkedCheckboxes = enabledCheckboxes.filter(cb => cb.checked);
                selectAllCheckbox.checked = enabledCheckboxes.length > 0 && enabledCheckboxes.length === checkedCheckboxes.length;
            }
            
            // 数量增减按钮
            document.querySelectorAll('.decrease-btn').forEach(btn => {
                btn.addEventListener('click', function() {
                    const input = this.parentElement.querySelector('.quantity-input');
                    const currentValue = parseInt(input.value);
                    if (currentValue > 1) {
                        input.value = currentValue - 1;
                        updateQuantity(this.closest('.cart-item').dataset.productId, input.value);
                    }
                });
            });
            
            document.querySelectorAll('.increase-btn').forEach(btn => {
                btn.addEventListener('click', function() {
                    const input = this.parentElement.querySelector('.quantity-input');
                    const currentValue = parseInt(input.value);
                    const maxValue = parseInt(input.getAttribute('max'));
                    if (currentValue < maxValue) {
                        input.value = currentValue + 1;
                        updateQuantity(this.closest('.cart-item').dataset.productId, input.value);
                    }
                });
            });
            
            // 数量输入框变化
            document.querySelectorAll('.quantity-input').forEach(input => {
                input.addEventListener('change', function() {
                    const value = parseInt(this.value);
                    const minValue = parseInt(this.getAttribute('min'));
                    const maxValue = parseInt(this.getAttribute('max'));
                    
                    if (isNaN(value) || value < minValue) {
                        this.value = minValue;
                    } else if (value > maxValue) {
                        this.value = maxValue;
                    }
                    
                    updateQuantity(this.closest('.cart-item').dataset.productId, this.value);
                });
            });
            
            // 删除单个商品
            document.querySelectorAll('.delete-item').forEach(btn => {
                btn.addEventListener('click', function() {
                    if (confirm('确定要删除这个商品吗？')) {
                        const productId = this.closest('.cart-item').dataset.productId;
                        removeFromCart(productId);
                    }
                });
            });
            
            // 批量删除选中商品
            deleteSelectedBtn.addEventListener('click', function() {
                const selectedItems = Array.from(itemCheckboxes)
                    .filter(cb => cb.checked && !cb.disabled)
                    .map(cb => cb.closest('.cart-item').dataset.productId);
                
                if (selectedItems.length === 0) {
                    showToast('请先选择要删除的商品', 'warning');
                    return;
                }
                
                if (confirm(`确定要删除选中的 ${selectedItems.length} 个商品吗？`)) {
                    removeFromCartBatch(selectedItems);
                }
            });
            
            // 清空购物车
            clearCartBtn.addEventListener('click', function() {
                if (confirm('确定要清空购物车吗？')) {
                    clearCart();
                }
            });
            
            // 去结算
            checkoutBtn.addEventListener('click', function() {
                if (this.disabled) return;
                 
                 // 这里应该跳转到结算页面
                 // 暂时使用模拟数据
                 showToast('即将跳转到结算页面', 'info');
             });
            
            // 更新购物车统计信息
            function updateCartStatistics() {
                fetch('/shop/cart/statistics')
                    .then(response => response.json())
                    .then(data => {
                        if (data.success) {
                            const statistics = data.data;
                            document.querySelector('.summary-item:nth-child(1) span:last-child').textContent = statistics.totalItems;
                            document.querySelector('.summary-item:nth-child(2) span:last-child').textContent = statistics.selectedItems;
                            document.querySelector('.summary-item:nth-child(3) span:last-child').textContent = statistics.validItems;
                            document.querySelector('.summary-total span:last-child').innerHTML = '¥' + statistics.totalAmount.toFixed(2);
                            
                            // 更新结算按钮状态
                            checkoutBtn.disabled = statistics.selectedItems === 0 || statistics.validItems === 0;
                        }
                    })
                    .catch(error => console.error('更新购物车统计信息失败:', error));
            }
            
            // 更新单个商品选中状态
            function updateSelected(productId, selected) {
                fetch('/shop/cart/select', {
                    method: 'POST',
                    headers: {
                        'Content-Type': 'application/x-www-form-urlencoded',
                    },
                    body: `productId=${productId}&selected=${selected}`
                })
                .then(response => response.json())
                .then(data => {
                    if (!data.success) {
                        console.error('更新选中状态失败:', data.message);
                    }
                })
                .catch(error => console.error('更新选中状态失败:', error));
            }
            
            // 更新所有商品选中状态
            function updateSelectedAll(selected) {
                fetch('/shop/cart/selectAll', {
                    method: 'POST',
                    headers: {
                        'Content-Type': 'application/x-www-form-urlencoded',
                    },
                    body: `selected=${selected}`
                })
                .then(response => response.json())
                .then(data => {
                    if (!data.success) {
                        console.error('更新全选状态失败:', data.message);
                    }
                })
                .catch(error => console.error('更新全选状态失败:', error));
            }
            
            // 更新商品数量
            function updateQuantity(productId, quantity) {
                fetch('/shop/cart/update', {
                    method: 'POST',
                    headers: {
                        'Content-Type': 'application/x-www-form-urlencoded',
                    },
                    body: `productId=${productId}&quantity=${quantity}`
                })
                .then(response => response.json())
                .then(data => {
                    if (data.success) {
                        // 更新小计金额
                        const cartItem = document.querySelector(`.cart-item[data-product-id="${productId}"]`);
                        const price = parseFloat(cartItem.querySelector('.cart-item-price span').textContent);
                        const subtotal = price * parseInt(quantity);
                        cartItem.querySelector('.cart-item-subtotal span').textContent = subtotal.toFixed(2);
                        
                        // 更新统计信息
                        updateCartStatistics();
                    } else {
                        console.error('更新数量失败:', data.message);
                        // 恢复原数量
                        location.reload();
                    }
                })
                .catch(error => {
                    console.error('更新数量失败:', error);
                    location.reload();
                });
            }
            
            // 删除单个商品
            function removeFromCart(cartId) {
                if (confirm('确定要删除这个商品吗？')) {
                    fetch(`/shop/cart/remove/${cartId}`, {
                        method: 'DELETE'
                    })
                    .then(response => response.json())
                    .then(data => {
                        if (data.success) {
                            showToast('商品已从购物车中移除', 'success');
                            loadCartItems();
                        } else {
                            showToast('删除商品失败: ' + data.message, 'danger');
                        }
                    })
                    .catch(error => {
                        console.error('Error:', error);
                        showToast('删除商品失败，请重试', 'danger');
                    });
                }
            }
            
            // 批量删除商品
            function removeFromCartBatch(productIds) {
                const formData = new FormData();
                productIds.forEach(id => formData.append('productIds', id));
                
                fetch('/shop/cart/removeBatch', {
                    method: 'POST',
                    body: formData
                })
                .then(response => response.json())
                .then(data => {
                    if (data.success) {
                        showToast(`成功删除 ${productIds.length} 个商品`, 'success');
                        
                        // 移除商品行
                        productIds.forEach(productId => {
                            const cartItem = document.querySelector(`.cart-item[data-product-id="${productId}"]`);
                            if (cartItem) cartItem.remove();
                        });
                        
                        // 更新统计信息
                        updateCartStatistics();
                        
                        // 检查购物车是否为空
                        if (document.querySelectorAll('.cart-item').length === 0) {
                            location.reload();
                        }
                    } else {
                        console.error('批量删除商品失败:', data.message);
                        showToast('批量删除商品失败: ' + data.message, 'danger');
                    }
                })
                .catch(error => {
                    console.error('批量删除商品失败:', error);
                    showToast('批量删除商品失败，请重试', 'danger');
                });
            }
            
            // 加载购物车商品
            function loadCartItems() {
                fetch('/shop/cart')
                    .then(response => response.text())
                    .then(html => {
                        // 这里可以解析HTML并更新购物车部分，但为了简化，直接刷新页面
                        location.reload();
                    })
                    .catch(error => {
                        console.error('加载购物车失败:', error);
                        location.reload();
                    });
            }
            
            // 清空购物车
            function clearCart() {
                fetch('/shop/cart/clear', {
                    method: 'POST'
                })
                .then(response => response.json())
                .then(data => {
                    if (data.success) {
                        showToast('购物车已清空', 'success');
                        setTimeout(() => {
                            location.reload();
                        }, 1000);
                    } else {
                        console.error('清空购物车失败:', data.message);
                        showToast('清空购物车失败: ' + data.message, 'danger');
                    }
                })
                .catch(error => {
                    console.error('清空购物车失败:', error);
                    showToast('清空购物车失败，请重试', 'danger');
                });
            }
        });
    </script>
</body>
</html>